function [ logicI,logicB ] = distinguishBoundary( position, distance )
% get the boundary of bird clusters, logic vector as output
% logicI means inside the cluster and logicB mens border
global boundaryPlot

num = length(position);
logicB = zeros(1,num) == ones(1,num);
radiuVisible = max(max(distance))/3;
cosStdTheta = -0.7; % cosStdTheta bigger ,Standand theta smaller and condition more strict.

for i = 1:num
    setLogic = zeros(1,num) == ones(1,num);
    for j = 1:num
         if distance(i,j)<radiuVisible
            setLogic(j) = true;
         end
    end
     numInR = sum(setLogic); % include itself
     posRela = position(setLogic,:) - repmat(position(i,:),numInR,1);
     normPosRela = (sum(posRela.*posRela,2)).^0.5; % column vector
     posRelaUnit = [posRela(:,1)./normPosRela,posRela(:,2)./normPosRela,posRela(:,3)./normPosRela];
     cosTheta = posRelaUnit*posRelaUnit'; % diag = 1
     if max(min(cosTheta))>cosStdTheta
         logicB(i) = true;
     end
     %numInRMa(i) =numInR;
end
logicI = ~logicB;

if boundaryPlot == 1
    figure(1)
    plot3(position(logicB,1),position(logicB,2),position(logicB,3),'r.')
    hold on 
    plot3(position(logicI,1),position(logicI,2),position(logicI,3),'g.')
    hold off
    text(min(position(:,1)),min(position(:,2)),min(position(:,3)),num2str(sum(logicB)))
end

end

